package com.example.figurehecheng.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.figurehecheng.common.context.BaseContext;
import com.example.figurehecheng.common.result.PageResult;
import com.example.figurehecheng.domain.dto.OrderPageDTO;
import com.example.figurehecheng.domain.entity.Orders;
import com.example.figurehecheng.domain.vo.TurnoverReportVO;
import com.example.figurehecheng.domain.vo.TurnoverVO;
import com.example.figurehecheng.mapper.OrderMapper;
import com.example.figurehecheng.mapper.UserMapper;
import com.example.figurehecheng.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.time.temporal.TemporalAdjusters;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 宇科工作室
 * @since 2024-10-18
 */
@Service
@RequiredArgsConstructor
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements IOrderService {

    private final OrderMapper orderMapper;

    //完成订单Complete the order
    private static final Integer COMPLETE_THE_ORDER = 2;

    /**
     * 订单查询
     * @param orderPageDTO
     * @return
     */
    @Override
    public PageResult selectOrderPage(OrderPageDTO orderPageDTO) {
        Page<Orders> page = new Page<>(orderPageDTO.getPageNum(), orderPageDTO.getPageSize());
        LambdaQueryWrapper<Orders> orderLambdaQueryWrapper = new LambdaQueryWrapper<Orders>()
                .eq(Orders::getMerchantId, BaseContext.getCurrentId())
                .eq(StrUtil.isNotBlank(orderPageDTO.getOrderNumber()), Orders::getOrderNumber, orderPageDTO.getOrderNumber())
                .between(orderPageDTO.getBeganTime() != null && orderPageDTO.getEndTime() != null, Orders::getOrderTime, orderPageDTO.getBeganTime(), orderPageDTO.getEndTime())
                .orderByDesc(Orders::getOrderTime);
        Page<Orders> orderPage = orderMapper.selectPage(page, orderLambdaQueryWrapper);

        List<Orders> records = orderPage.getRecords();

        long total = orderPage.getTotal();
        
        return new PageResult(total,records);
    }


    /**
     * 完成订单
     * @param orderId
     * @return
     */
    @Override
    public void complete(Integer orderId) {
        Orders orders = new Orders();
        orders.setOrderId(orderId);
        orders.setStatue(COMPLETE_THE_ORDER);
        orderMapper.updateById(orders);
    }

    /**
     * 获取今天，这周，这个月，今年收入总金额
     * @return
     */
    @Override
    public TurnoverVO getTurnover() {

        // 获取时间
        List<LocalDateTime> localDateTimes = new ArrayList<>();

        // 今天日期
        LocalDateTime today = LocalDateTime.of(LocalDate.now(), LocalTime.MIDNIGHT);
        localDateTimes.add(today);

        // 获取本周第一天
        LocalDate weekStart = LocalDate.now().with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
        LocalDateTime week = LocalDateTime.of(weekStart, LocalTime.MIDNIGHT);
        localDateTimes.add(week);

        // 获取本个月第一天
        LocalDate monthStart = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
        LocalDateTime month = LocalDateTime.of(monthStart, LocalTime.MIDNIGHT);
        localDateTimes.add(month);

        // 获取今年第一天
        LocalDate yearStart = LocalDate.now().with(TemporalAdjusters.firstDayOfYear());
        LocalDateTime year = LocalDateTime.of(yearStart, LocalTime.MIDNIGHT);
        localDateTimes.add(year);

        // 查询今天，这周，这个月，今年收入总金额
        List<BigDecimal> turnover = new ArrayList<>();

        for (LocalDateTime localDateTime : localDateTimes) {
            BigDecimal bigDecimal = orderMapper.getTurnover(localDateTime, BaseContext.getCurrentId(), COMPLETE_THE_ORDER);
            turnover.add(bigDecimal);
        }

        TurnoverVO turnoverVO = new TurnoverVO();
        turnoverVO.setIncomeToday(turnover.get(0));
        turnoverVO.setIncomeWeek(turnover.get(1));
        turnoverVO.setIncomeMonth(turnover.get(2));
        turnoverVO.setIncomeYear(turnover.get(3));

        return turnoverVO;
    }

    /**
     * 营业额统计
     * @param
     * @param
     * @return
     */
    @Override
    public List getTurnoverStatistics() {
        // 获取今年第一天
        //1.1
        LocalDate yearStart = LocalDate.now().with(TemporalAdjusters.firstDayOfYear());

        //一月第一天00点
        LocalDateTime firstDayTime = LocalDateTime.of(yearStart, LocalTime.MIDNIGHT);

        LocalDateTime firstDayTime1 = LocalDateTime.of(yearStart, LocalTime.MIDNIGHT);
        List<BigDecimal> turnover = new ArrayList<>();
        while (!firstDayTime.equals(firstDayTime1.plusYears(1))){
            //下月第一天00点
            LocalDateTime lastDayTime = firstDayTime.plusMonths(1);
            BigDecimal bigDecimal = orderMapper.getTurnoverStatistics(firstDayTime,lastDayTime, BaseContext.getCurrentId(),COMPLETE_THE_ORDER);
            if (bigDecimal == null){
                turnover.add(new BigDecimal("0.00"));
            }else {
                turnover.add(bigDecimal);
            }
            firstDayTime = firstDayTime.plusMonths(1);
        }
        return turnover;
    }

}
